<template>
  <div class="content">
    <header>
      <van-nav-bar
        title="登录"
        left-arrow
        @click-left="$router.back()"
      />
    </header>
    <div class="content">
      <van-field
        v-model="tel"
        style="margin-top: 20px"
        placeholder="请输入手机号码/邮箱/用户名" />
      <van-field
        v-model="password"
        style="margin-top: 20px"
        placeholder="请输入密码" />
      <van-button
        round
        block
        @click="docheckphoneFN"
        :disabled="!flag"
        color="#ff6666"
        style="margin-top: 20px">下一步
      </van-button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'

import {
  Form,
  Field,
  Button,
  Dialog,
  NavBar,
  Toast
} from 'vant'

import { docheckphone } from '@/api/register'
import { checkLogin } from '@/api/login'

Vue.use(Form)
Vue.use(Field)
Vue.use(Button)
Vue.use(Dialog)
Vue.use(NavBar)
Vue.use(Toast)

export default {
  name: 'login',
  data () {
    return {
      password: '123@QQ.com',
      tel: '18919382500'
    }
  },
  computed: {
    flag: function () {
      return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/.test(this.tel) && /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/.test(this.password)
    }
  },
  methods: {
    async docheckphoneFN () {
      const res = await docheckphone({ tel: this.tel })
      if (res.data.code === '10005') {
        checkLogin({ loginname: this.tel, password: this.password }).then(res => {
          console.log(res.data)
          if (res.data.code === '10011') {
            Toast('用户名或密码错误')
          } else {
            Toast('登陆成功')
            localStorage.setItem('token', res.data.data.token)
            localStorage.setItem('userid', res.data.data.userid)
            localStorage.setItem('isLogin', true)
            this.$router.back()
          }
        })
      } else {
        Dialog.confirm({
          message: '该账户还未注册',
          confirmButtonText: '去登陆',
          cancelButtonColor: '更换手机号并重新登录'
        })
          .then(() => {
            // on confirm
            this.$router.push('register')
          })
          .catch(() => {
            // on cancel
          })
      }
    }
  }
}
</script>

<style scoped>

</style>
